package com.JZ.QM.controller;

import com.JZ.QM.common.entity.BankAccountEntity;
import com.JZ.QM.common.entity.UserAccountEntity;
import com.JZ.QM.common.entity.UserInfoEntity;
import com.JZ.QM.common.utils.CommonResult;
import com.JZ.QM.dto.BankAccountDTO;
import com.JZ.QM.dto.RechargeAndWithdrawalDTO;
import com.JZ.QM.service.BankAccountService;
import com.JZ.QM.service.UserAccountService;
import com.JZ.QM.service.UserInfoService;
import com.JZ.QM.utils.BankAccountUtil;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * @author: cyc
 * @email cyc@gmail.com
 * @date 2020/6/24 11:37
 */
@RestController
@RefreshScope
@Slf4j
@RequestMapping(value="/bankAccount")
public class BankAccountController {
    @Resource
    UserAccountService userAccountService;
    @Resource
    BankAccountService bankAccountService;
    @Resource
    UserInfoService userInfoService;

    /**
     *开通银行存管
     * @return
     */
    @PostMapping("/openBankAccount")
    public CommonResult openBankAccount(@Valid @RequestBody BankAccountDTO bankAccountDTO) throws JSONException {
        //用户对应的账户id
        Long accountId;
        //银行卡存在标识
        BankAccountEntity bankAccountEntity = new BankAccountEntity();
        //银行账户更新状态标识
        boolean bankAccountUpdateFlag = false;
        boolean authenticationFlag = false;
        UserInfoEntity userInfoEntity = new UserInfoEntity();

        userInfoEntity = userInfoService.getById(bankAccountDTO.getUserId());
        if (userInfoEntity == null){
            return CommonResult.error(201,"该用户不存在");
        } else {
            if (userInfoEntity.getUserName() == null || userInfoEntity.getUserCard() == null){
                return CommonResult.error(201,"请进行实名认证");
            } else {
                if( bankAccountDTO.getUserName().equals(userInfoEntity.getUserName()) &&
                        bankAccountDTO.getUserCard().equals(userInfoEntity.getUserCard())){
                    //通过用户id获取账户id
                    accountId=userAccountService.getAccount(bankAccountDTO.getUserId()).getAccountId();
                    //查询银行卡信息是否存在
                    bankAccountEntity=bankAccountService.getBankAccountCard(bankAccountDTO.getBankAccountCard());
                    if (bankAccountEntity == null){
                        //更新用户信息
                        bankAccountDTO.setBankHotLine(BankAccountUtil.getHotLine(bankAccountDTO.getAccountBankName()));
                        bankAccountDTO.setAccountId(accountId);
                        System.out.println("账户id为"+accountId);
                        System.out.println(bankAccountDTO.toString());
                        bankAccountUpdateFlag=bankAccountService.updateBankAccount(bankAccountDTO);
                        if (bankAccountUpdateFlag){
                            return CommonResult.success("该银行存管已经成功开通");
                        } else {
                            return CommonResult.error(201,"账户信息更新失败");
                        }
                    } else {
                        return CommonResult.error(201,"该账户信息已经注册绑定");
                    }
                } else {
                    return CommonResult.error(201,"用户身份校验失败，请重新输入");
                }
            }

        }

    }

    /**
     * 通过用户id对应的账户基本信息
     * @param userId 用户id
     * @return
     */
    @RequestMapping("/bankAccountInfo")
    public CommonResult getBankAccountInfo(Long userId){
        //账户id
        UserAccountEntity userAccountEntity;
        //银行账户基本信息列表
        ArrayList<HashMap<String,Object>> result=new ArrayList<>();

        userAccountEntity=userAccountService.getAccount(userId);
        if (userAccountEntity == null){
            return CommonResult.error(201,"该用户不存在");
        } else {
            //查询银行账户列表
            result= bankAccountService.getBankAccountList(userAccountEntity.getAccountId());
            if (result.isEmpty()){
               return CommonResult.success("用户尚未绑定银行卡账户").put("bankAccountList",new ArrayList<>());
            } else {
                return CommonResult.success().put("bankAccountList",result);
            }
        }
    }

    /**
     * 银行卡向平台账户充值
     * @param rechargeAndWithdrawalDTO 充值，提现数据传输对象
     * @return
     */
    @PostMapping("/recharge")
    public CommonResult recharge(@RequestBody @Valid RechargeAndWithdrawalDTO rechargeAndWithdrawalDTO){
        //用户对应的账户id
        UserAccountEntity userAccountEntity=new UserAccountEntity();
        //用户充值状态
        boolean rechargeState=false;
        BankAccountEntity bankAccountEntity=new BankAccountEntity();
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();

        //获取用户对应的账户信息
        userAccountEntity=userAccountService.getAccount(rechargeAndWithdrawalDTO.getUserId());
        bankAccountEntity=bankAccountService.getBankAccountCard(rechargeAndWithdrawalDTO.getBankAccountCard());
        if (userAccountEntity !=null && bankAccountEntity !=null){
           if (rechargeAndWithdrawalDTO.getBankAccountCard().equals(bankAccountEntity.getBankAccountCard()) &&
                    bCryptPasswordEncoder.matches(rechargeAndWithdrawalDTO.getUserPassword(),userAccountEntity.getUserPassword())){
                if(rechargeAndWithdrawalDTO.getTradeMoney().compareTo(bankAccountEntity.getBankAccountAmoount()) ==1){
                    return CommonResult.error(201,"账户余额不足，余额仅剩"+bankAccountEntity.getBankAccountAmoount().toString()+"元");
                } else {
                    rechargeAndWithdrawalDTO.setBankAccountId(bankAccountEntity.getBankAccountId());
                    rechargeAndWithdrawalDTO.setUserAccountId(userAccountEntity.getAccountId());
                    rechargeAndWithdrawalDTO.setBankAccountAmoount(bankAccountEntity.getBankAccountAmoount().subtract(rechargeAndWithdrawalDTO.getTradeMoney()));
                    rechargeAndWithdrawalDTO.setUserAccountAmoount(userAccountEntity.getAccountAmoount().add(rechargeAndWithdrawalDTO.getTradeMoney()));
                    //账户充值
                    rechargeState=bankAccountService.recharge(rechargeAndWithdrawalDTO,1);
                    if(rechargeState){
                        return CommonResult.success("账户充值成功");
                    } else {
                        return CommonResult.error(201,"充值发生异常，请稍后再试");
                    }
                }
            } else {
                return CommonResult.error(201,"银行账户信息审核失败,请确认已开通该账户");
            }
        } else {
            return CommonResult.error(201,"该用户未开通银行账户，系统出现异常");
        }
    }

    /**
     *平台账户向银行卡提现
     * @param rechargeAndWithdrawalDTO 充值，提现数据传输对象
     * @return
     */
    @PostMapping("/withdraw")
    public CommonResult withdraw(@RequestBody @Valid RechargeAndWithdrawalDTO rechargeAndWithdrawalDTO){
        //用户对应的账户id
        UserAccountEntity userAccountEntity=new UserAccountEntity();
        //用户充值状态
        boolean withdrawState=false;
        BankAccountEntity bankAccountEntity=new BankAccountEntity();
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();

        //获取用户对应的账户信息
        userAccountEntity=userAccountService.getAccount(rechargeAndWithdrawalDTO.getUserId());

        if (userAccountEntity !=null){
            //获取账户实体类
            bankAccountEntity=bankAccountService.getBankAccountCard(rechargeAndWithdrawalDTO.getBankAccountCard());
            //判断密码是否相等
            if (rechargeAndWithdrawalDTO.getBankAccountCard().equals(bankAccountEntity.getBankAccountCard()) &&
                bCryptPasswordEncoder.matches(rechargeAndWithdrawalDTO.getUserPassword(),userAccountEntity.getUserPassword())){
                //判断账户余额是否充足
                if(rechargeAndWithdrawalDTO.getTradeMoney().compareTo(userAccountEntity.getAccountAmoount()) ==1){
                    return CommonResult.error(201,"平台账户余额不足，余额仅剩"+userAccountEntity.getAccountAmoount().toString()+"元");
                    //余额充足
                } else {
                    rechargeAndWithdrawalDTO.setBankAccountId(bankAccountEntity.getBankAccountId());
                    rechargeAndWithdrawalDTO.setUserAccountId(userAccountEntity.getAccountId());
                    rechargeAndWithdrawalDTO.setBankAccountAmoount(bankAccountEntity.getBankAccountAmoount().add(rechargeAndWithdrawalDTO.getTradeMoney()));
                    rechargeAndWithdrawalDTO.setUserAccountAmoount(userAccountEntity.getAccountAmoount().subtract(rechargeAndWithdrawalDTO.getTradeMoney()));
                    //账户提现
                    withdrawState=bankAccountService.recharge(rechargeAndWithdrawalDTO,0);

                    if(withdrawState){
                        return CommonResult.success("账户提现成功");
                    } else {
                        return CommonResult.error(201,"提现发生异常，请稍后再试");
                    }
                }
            } else {
                return CommonResult.error(201,"银行账户信息审核失败,请确认已开通该账户");
            }
        } else {
            return CommonResult.error(201,"该用户未开通银行账户，系统出现异常");
        }
    }
}
